//
//  SDHSportsMatchVC.m
//  SDHSportsNews
//
//  Created by MichaelShan on 2021/3/3.
//

#import "SDHSportsMatchVC.h"
#import "SDHSportsBaseCell.h"
#import "SDHSportsMatchDateCell.h"
#import "SDHSportsMatchInfoCell.h"
#import "SDHSportsMatchModel.h"
#import "SDHSportsMatchSoccerModel.h"
#import "SDHSportsMatchHeaderView.h"
#import "SDHSportsNetRequest.h"
#import "SDHSportsRequest.h"
#import "MJRefresh.h"
#import "SDHSportsFileManager.h"
#import "NSMutableDictionary+SDHSports.h"
#import "SDHSportsMatchBasketModel.h"
#import "SDHSportsTestVC.h"
#import "SDHSportsTeamInfoVC.h"
#import "SDHSportsMatchLiveVC.h"

#define kMatchDataFilename  @"matchdata"
static const NSString *kCellDateIdentifier = @"date";
static const NSString *kCellMatchIdentifier = @"match";

@interface SDHSportsMatchVC () <UITableViewDelegate, UITableViewDataSource> {
    SDHSportsNetRequest *netRequest;
    NSString *requestUrl;
    NSInteger dtype;
    BOOL isRefresh;
}

@property (nonatomic, strong) SDHSportsMatchHeaderView *headerView;
@property (nonatomic, strong) UITableView *soccerTable;
@property (nonatomic, strong) UITableView *basketTable;
@property (nonatomic, copy) NSMutableDictionary *dataTennisDict;
@property (nonatomic, copy) NSMutableDictionary *dataSoccerDict;
@property (nonatomic, copy) NSMutableArray *dataBasketballArray;
@property (nonatomic, copy) NSMutableArray *dataBaseballArray;

@end

@implementation SDHSportsMatchVC

- (id)init {
    if (self = [super init]) {
        dtype = 1; //1足球，2篮球,3棒球,5网球
        isRefresh = YES;
        //http://jsuywu8.com/guojitiyu/Tiyu1/getSchedule
        //http://jsuywu8.com/guojitiyu/Tiyusaishi/getBangqiu
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    __weak typeof(self) weakSelf = self;

    SDHSportsMatchHeaderView *hView = [SDHSportsMatchHeaderView new];
    hView.backgroundColor = [UIColor clearColor];
    hView.headerClick = ^(NSInteger index) {
        [weakSelf headerClick:index];
    };
    [self.view addSubview:hView];
    self.headerView = hView;
    
    UITableView *table = [UITableView new];
    table.delegate = self;
    table.dataSource = self;
//    table.backgroundColor = [UIColor redColor];
    table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:table];
    self.soccerTable = table;
    
    table = [UITableView new];
    table.delegate = self;
    table.dataSource = self;
//    table.backgroundColor = [UIColor redColor];
    table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:table];
    self.basketTable = table;
    
    UIView *superview = self.view;
    [hView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superview).insets(UIEdgeInsetsZero).priorityLow();
        make.top.equalTo(superview).offset(20);
        make.left.equalTo(superview).offset(10);
        make.right.equalTo(superview).offset(-10);
        make.height.equalTo(@120);
        make.bottom.mas_equalTo(table.mas_top);
    }];
    
    [self.soccerTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superview).insets(UIEdgeInsetsZero).priorityLow();
        make.top.mas_equalTo(hView.mas_bottom);
    }];
    
    [self.basketTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superview).insets(UIEdgeInsetsZero).priorityLow();
        make.top.mas_equalTo(hView.mas_bottom);
    }];
    self.basketTable.hidden = YES;
    
    self.soccerTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headerRefreshing];
    }];
    self.basketTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headerRefreshing];
    }];
    
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)headerClick:(NSInteger)index {
    if (0 == index || 1 == index) {
        self.soccerTable.hidden = NO;
        self.basketTable.hidden = YES;
    } else {
        self.soccerTable.hidden = YES;
        self.basketTable.hidden = NO;
    }
    
    [self loadData];
}

- (void)headerRefreshing {
    isRefresh = YES;
    [self loadData];
}

- (void)endLoading {
    [MBProgressHUD hideHUD];
    
    if (0 == _headerView.selectedIndex || 1 == _headerView.selectedIndex) {
        [self.soccerTable reloadData];
        [self.soccerTable.mj_header endRefreshing];
    } else {
        [self.basketTable reloadData];
        [self.basketTable.mj_header endRefreshing];
    }
}

- (void)parseSoccerData:(NSDictionary *)dict {
    NSDictionary *matchDic = [dict objectForKey:@"data"];
    if (![matchDic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    NSArray *arrGoing = matchDic[@"going"][@"matches"];
    NSArray *arrComing = matchDic[@"uncoming"][@"matches"];
    NSArray *arrFinished = matchDic[@"finished"][@"matches"];
    NSArray *arrUnknown = matchDic[@"finished"][@"unknown"];
    NSArray *leagueMatchs = matchDic[@"leagueMatchs"];
    
    // 1: ongoing, 2: coming, 3: finished, 4: to be confirmed
    NSMutableDictionary *tmpDic = [self getDataFromArray:arrGoing type:1];
    NSMutableDictionary *tmpDic2 = [self getDataFromArray:arrComing type:2];
    NSMutableDictionary *tmpDic3 = [self getDataFromArray:arrFinished type:3];
    NSMutableDictionary *tmpDic4 = [self getDataFromArray:arrUnknown type:4];
    NSMutableDictionary *tmpDic5 = [self getDataFromArray:leagueMatchs type:5];
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic mergingWithDictionary:tmpDic];
    [dataDic mergingWithDictionary:tmpDic2];
    [dataDic mergingWithDictionary:tmpDic3];
    [dataDic mergingWithDictionary:tmpDic4];
    
    if (0 == _headerView.selectedIndex) {
        self.dataSoccerDict = dataDic;
    } else if (1 == _headerView.selectedIndex) {
        self.dataTennisDict = dataDic;
    }
}

- (void)parseBasketData:(NSDictionary *)dict {
    NSArray *array = [dict objectForKey:@"data"];
    if (![array isKindOfClass:[NSArray class]]) {
        return;
    }
    
    NSMutableArray *dataArr = [SDHSportsMatchBasketModel mj_objectArrayWithKeyValuesArray:array];
    
    if (2 == _headerView.selectedIndex) {
        self.dataBasketballArray = dataArr;
    } else if (3 == _headerView.selectedIndex) {
        self.dataBaseballArray = dataArr;
    }
}

- (void)parseData:(NSDictionary *)dict {
    NSString *filename = [NSString stringWithFormat:@"%@_%d", kMatchDataFilename, dtype];
    [SDHSportsFileManager saveDict:dict toFileName:filename];
    
    if (isRefresh) {
        if (0 == _headerView.selectedIndex) {
            self.dataSoccerDict = [NSMutableDictionary dictionary];
        } else if (1 == _headerView.selectedIndex) {
            self.dataTennisDict = [NSMutableDictionary dictionary];
        } else if (2 == _headerView.selectedIndex) {
            self.dataBasketballArray = [NSMutableArray array];
        } else {
            self.dataBaseballArray = [NSMutableArray array];
        }
        isRefresh = NO;
    }

    if (dtype == 1 || dtype == 2) {
        [self parseSoccerData:dict];
    } else {
        [self parseBasketData:dict];
    }
}

- (NSMutableDictionary *)getDataFromArray:(NSArray *)arrData type:(NSInteger)type {
    if (arrData == nil || arrData.count == 0) {
        return nil;
    }
    NSMutableDictionary *dataDic = [NSMutableDictionary new];
    NSString *dateStr = nil;
    NSArray *array = [SDHSportsMatchSoccerModel mj_objectArrayWithKeyValuesArray:arrData];
    for (SDHSportsMatchSoccerModel *model in array) {
        NSDate *tmpdate = [NSDate dateFromString:model.curMatchTime withFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        dateStr = [formatter stringFromDate:tmpdate];
        if (dateStr) {
            [dataDic setObject:@[] forKey:dateStr];
        }
    }

    NSArray *allKeys = [dataDic allKeys];
    for (NSString *tmpKey in allKeys) {
        for (SDHSportsMatchSoccerModel *model in array) {
            NSDate *tmpdate = [NSDate dateFromString:model.curMatchTime withFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            dateStr = [formatter stringFromDate:tmpdate];
            if ([tmpKey isEqualToString:dateStr]) {
                NSMutableArray *array = [NSMutableArray array];
                NSArray *arr = [dataDic objectForKey:tmpKey];
                if (nil != arr) {
                    [array addObjectsFromArray:arr];
                }
                
                model.state = type;
                [array addObject:model];
                [dataDic setObject:array forKey:tmpKey];
            }
        }
    }
    
    return dataDic;
}

- (NSDictionary *)getDataDict {
    NSDictionary *dict = self.dataSoccerDict;
    if (0 == _headerView.selectedIndex) {
        dict = self.dataSoccerDict;
    } else if (1 == _headerView.selectedIndex) {
        dict = self.dataTennisDict;
    }
    return dict;
}

- (NSArray *)getDataArr {
    NSArray *array = self.dataBasketballArray;
    if (2 == _headerView.selectedIndex) {
        array = self.dataBasketballArray;
    } else if (3 == _headerView.selectedIndex) {
        array = self.dataBaseballArray;
    }
    
    return array;
}

- (void)loadData {
    //1足球，2篮球,3棒球,5网球
    //http://jsuywu8.com/guojitiyu/Tiyu1/getSchedule
    //http://jsuywu8.com/guojitiyu/Tiyusaishi/getBangqiu
    NSString *getSchedule = @"http://jsuywu8.com/guojitiyu/Tiyu1/getSchedule";
    NSString *getBangqiu = @"http://jsuywu8.com/guojitiyu/Tiyusaishi/getBangqiu";
    BOOL needLoad = YES;
    if (0 == _headerView.selectedIndex) {
        dtype = 1;
        requestUrl = getSchedule;
        if ([[self.dataSoccerDict allKeys] count] > 0) {
            needLoad = NO;
        }
    } else if (1 == _headerView.selectedIndex) {
        dtype = 2;
        requestUrl = getSchedule;
        if ([[self.dataTennisDict allKeys] count] > 0) {
            needLoad = NO;
        }
    } else if (2 == _headerView.selectedIndex) {
        dtype = 3;
        requestUrl = getBangqiu;
        if ([self.dataBasketballArray count] > 0) {
            needLoad = NO;
        }
    } else if (3 == _headerView.selectedIndex) {
        dtype = 5;
        requestUrl = getBangqiu;
        if ([self.dataBaseballArray count] > 0) {
            needLoad = NO;
        }
    }
    
    [MBProgressHUD showLoading];
    if (isRefresh || needLoad) {
        SDHSportsRequest *request = [SDHSportsRequest new];
        request.requestUrl = requestUrl;
        request.requestPara = @{@"dtype":@(dtype)};
        
        __weak typeof(self) weakSelf = self;
        [[SDHSportsNetRequest sharedRequest] sendRequest:request returnValueBlock:^(id  _Nonnull obj) {
            [weakSelf parseData:obj];
            [weakSelf endLoading];
        } errorBlock:^(id  _Nonnull obj) {
            [weakSelf endLoading];
        } failureBlock:^{
            [weakSelf endLoading];
        }];
    } else {
        [self endLoading];
    }
}

- (void)enterTeamInfoVc:(NSDictionary *)dic {
    SDHSportsTeamInfoVC *vc = [[SDHSportsTeamInfoVC alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.teamInfoDic = dic;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma - uitableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger count = 0;
    if (tableView == self.soccerTable) {
        if (0 == _headerView.selectedIndex) {
            count = [[self.dataSoccerDict allKeys] count];
        } else {
            count = [[self.dataTennisDict allKeys] count];
        }
    } else {
        count = 1;
    }
    
    return count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 0;
    if (tableView == self.soccerTable) {
        NSDictionary *dict = self.dataSoccerDict;
        if (0 == _headerView.selectedIndex) {
            dict = self.dataSoccerDict;
        } else if (1 == _headerView.selectedIndex) {
            dict = self.dataTennisDict;
        }
        NSString *key = [[dict allKeys] objectAtIndex:section];
        count = [[dict objectForKey:key] count] + 1;
    } else {
        if (2 == _headerView.selectedIndex) {
            count = self.dataBasketballArray.count;
        } else {
            count = self.dataBaseballArray.count;
        }
    }
    
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 120;
    if (tableView == self.soccerTable) {
        if (indexPath.row == 0) {
            height = 50;
        }
    }
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifer = kCellDateIdentifier;
    SDHSportsBaseCell *cell = nil;
    if (tableView == self.soccerTable && 0 == indexPath.row) {
        identifer = kCellDateIdentifier;
        cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[SDHSportsMatchDateCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    } else {
        identifer = kCellMatchIdentifier;
        cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[SDHSportsMatchInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
        }
    }
    
    if (tableView == self.soccerTable && 0 == indexPath.row) {
        NSDictionary *dataDict = [self getDataDict];
        NSString *key = [[dataDict allKeys] objectAtIndex:indexPath.section];
        [cell updateContent:key];
    } else {
        if (tableView == self.soccerTable) {
            NSDictionary *dataDict = [self getDataDict];
            NSString *key = [[dataDict allKeys] objectAtIndex:indexPath.section];
            SDHSportsMatchSoccerModel *modal = [[dataDict objectForKey:key] objectAtIndex:indexPath.row-1];
            [cell updateContent:modal];
            
            SDHSportsMatchInfoCell *tmpCell = (SDHSportsMatchInfoCell *)cell;
            tmpCell.leftClick = ^(SDHSportsMatchSoccerModel *model) {
                NSDictionary *dic = @{@"team_id":model.guestTeamId, @"league_id":model.leagueId};
                [self enterTeamInfoVc:dic];
            };
            tmpCell.rightClick = ^(SDHSportsMatchSoccerModel *model) {
                NSDictionary *dic = @{@"team_id":model.guestTeamId, @"league_id":model.leagueId};
                [self enterTeamInfoVc:dic];
            };
        } else {
            SDHSportsMatchBasketModel *modal = [[self getDataArr] objectAtIndex:indexPath.row];
            [cell updateContent:modal];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    SDHSportsTestVC *vc = [[SDHSportsTestVC alloc] initWithNibName:@"SDHSportsTestVC" bundle:nil];
//    [self.navigationController pushViewController:vc animated:YES];
    
    if (tableView == self.soccerTable) {
        NSDictionary *dataDict = [self getDataDict];
        NSString *key = [[dataDict allKeys] objectAtIndex:indexPath.section];
        SDHSportsMatchSoccerModel *model = [[dataDict objectForKey:key] objectAtIndex:indexPath.row-1];
        
        SDHSportsMatchLiveVC *vc = [[SDHSportsMatchLiveVC alloc] init];
        vc.model = model;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 圆角弧度半径
    CGFloat cornerRadius = 30.f;
    // 设置cell的背景色为透明，如果不设置这个的话，则原来的背景色不会被覆盖
    cell.backgroundColor = UIColor.clearColor;

    // 创建一个shapeLayer
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    CAShapeLayer *backgroundLayer = [[CAShapeLayer alloc] init]; //显示选中
    // 创建一个可变的图像Path句柄，该路径用于保存绘图信息
    CGMutablePathRef pathRef = CGPathCreateMutable();
    // 获取cell的size
    // 第一个参数,是整个 cell 的 bounds, 第二个参数是距左右两端的距离,第三个参数是距上下两端的距离
    CGRect bounds = CGRectInset(cell.bounds, 0, 0);

    // CGRectGetMinY：返回对象顶点坐标
    // CGRectGetMaxY：返回对象底点坐标
    // CGRectGetMinX：返回对象左边缘坐标
    // CGRectGetMaxX：返回对象右边缘坐标
    // CGRectGetMidX: 返回对象中心点的X坐标
    // CGRectGetMidY: 返回对象中心点的Y坐标

    // 这里要判断分组列表中的第一行，每组section的第一行，每组section的中间行

    // CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
    if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
                 CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
           }
    else if (indexPath.row == 0 && indexPath.section == 0) {
        // 初始起点为cell的左下角坐标
        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
        // 起始坐标为左下角，设为p，（CGRectGetMinX(bounds), CGRectGetMinY(bounds)）为左上角的点，设为p1(x1,y1)，(CGRectGetMidX(bounds), CGRectGetMinY(bounds))为顶部中点的点，设为p2(x2,y2)。然后连接p1和p2为一条直线l1，连接初始点p到p1成一条直线l，则在两条直线相交处绘制弧度为r的圆角。
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
        // 终点坐标为右下角坐标点，把绘图信息都放到路径中去,根据这些路径就构成了一块区域了
        CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
        CGPathCloseSubpath(pathRef);

    } else if (indexPath.section == [tableView numberOfSections]-1 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
        // 初始起点为cell的左上角坐标
        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
        // 添加一条直线，终点坐标为右下角坐标点并放到路径中去
        CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
    } else {
        // 添加cell的rectangle信息到path中（不包括圆角）
        CGPathAddRect(pathRef, nil, bounds);
    }
    // 把已经绘制好的可变图像路径赋值给图层，然后图层根据这图像path进行图像渲染render
    layer.path = pathRef;
    backgroundLayer.path = pathRef;
    // 注意：但凡通过Quartz2D中带有creat/copy/retain方法创建出来的值都必须要释放
    CFRelease(pathRef);
    // 按照shape layer的path填充颜色，类似于渲染render
    //     layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
    layer.fillColor = [UIColor whiteColor].CGColor;
//    layer.strokeColor = [UIColor lightGrayColor].CGColor;

    // view大小与cell一致
    UIView *roundView = [[UIView alloc] initWithFrame:bounds];
    // 添加自定义圆角后的图层到roundView中
    [roundView.layer insertSublayer:layer atIndex:0];
    roundView.backgroundColor = UIColor.clearColor;
    // cell的背景view
    cell.backgroundView = roundView;

    // 以上方法存在缺陷当点击cell时还是出现cell方形效果，因此还需要添加以下方法
    
    // 如果你 cell 已经取消选中状态的话,那以下方法是不需要的.
    UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:bounds];
    backgroundLayer.fillColor = [UIColor cyanColor].CGColor;
    [selectedBackgroundView.layer insertSublayer:backgroundLayer atIndex:0];
    selectedBackgroundView.backgroundColor = UIColor.clearColor;
    cell.selectedBackgroundView = selectedBackgroundView;
}

@end
